<template>
    <a-row>
        <!-- v-userAuth="'F2'" -->
        <a-row class='mytitle'>
            <!-- <a-icon :component="alarm" style="margin:0 .5rem 0 0"/> -->
            {{$t('Warning_info')}}
        </a-row>

        <NoAuthPage v-showNoAuth="'F2-1'" />

        <a-row style="margin:1em" v-userAuth="'F2-1'">
            <a-card hoverable>
                <div style="margin:0 0 1em 0; display: flex; justify-content: space-between; ">
                    <div style="display: inline-block">
                        <a-tooltip placement='bottom' v-userAuth="'F2-2'">
                            <template slot='title'>
                                <span>{{$t('Manual_repair')}}</span>
                            </template>
                            <a-button :disabled="selectedRowKeys.length==0" type='danger' @click="manualRepair">
                                <!-- <i class="icon icon-eliminate16f"></i> -->
                                <Iconfont class="icon" type="icon-eliminate16f"></Iconfont>
                                {{$t('Manual_repair')}}
                                <!-- <a-icon :component="eliminate"/> -->
                            </a-button>
                        </a-tooltip>
                    </div>
                    <div style="display: inline-block">
                        <div style="display: inline-block;">
                            <span>{{$t('Level')}}： </span>
                            <a-radio-group v-model="levelValue" button-style="solid" @change="changeLevel">
                                <a-radio-button :value="0">
                                {{$t('All')}}
                                </a-radio-button>
                                <a-radio-button :value="1">
                                {{$t('Urgent')}}
                                </a-radio-button>
                                <a-radio-button :value="2">
                                {{$t('Important')}}
                                </a-radio-button>
                                <a-radio-button :value="3">
                                {{$t('Warning')}}
                                </a-radio-button>
                            </a-radio-group>
                        </div>
                        <div style="display: inline-block; margin-left: 1rem">
                            <span>{{$t('Status')}}： </span>
                            <a-radio-group v-model="statusValue" button-style="solid" @change="changeStatus">
                                <a-radio-button :value="0">
                                    {{$t('All')}}
                                </a-radio-button>
                                <a-radio-button :value="1">
                                    {{ $t('Not_repaired') }}
                                </a-radio-button>
                                <a-radio-button :value="2">
                                    {{ $t('Already_fixed') }}
                                </a-radio-button>
                            </a-radio-group>
                        </div>
                        <div style="display: inline-block; margin-left: 1rem">
                            <span>{{$t('Occur') + $t('Time')}}： </span>
                            <a-range-picker
                                v-model="selectTime"
                                :show-time="{ format: 'HH:mm' }"
                                format="YYYY-MM-DD HH:mm"
                                :placeholder="[$t('Start-date'), $t('End-date')]"
                                @change="onChange"
                                @ok="onOk"
                                :locale="rangePickerLocal"
                            />
                        </div>
                        <a-button @click="reset" type="primary" style="margin-left: 1rem">{{$t('Reset')}}</a-button>
                    </div>
                </div>
                <a-table class="tabstyle" :columns="columns" :dataSource="alertData" size="small" 
                        :row-selection="rowSelection" rowKey="id" :pagination='pagination' :locale="defaultSetting">
                    <template slot="severity" slot-scope='severity'>
                        <span :class="severity === '严重' ? 'red-circle' : severity === '警告' ? 'orange-circle' : severity === '提示' ? 'yellow-circle' : ''"></span>
                        <span>{{ severity }}</span>
                        <!-- {{severity === '严重' ? $t('Urgent') : severity === '警告' ? $t('Important') : severity === '提示' ? $t('Warning') : severity}} -->
                        <!-- <a-tag :color="severity === '紧急' ? 'red' : severity === '重要' ? 'orange' : severity === '警告' ? 'yellow' : ''">
                            {{severity === '紧急' ? $t('Urgent') : severity === '重要' ? $t('Important') : severity === '警告' ? $t('Warning') : severity}}
                        </a-tag> -->
                    </template>
                    <template slot="repair_status" slot-scope='repair_status'>
                        <span :class="repair_status === 0 ? 'red-circle' : 'green-circle'"></span>
                        {{ repair_status === 0 ? $t('Not_repaired') : $t('Already_fixed') }}
                        <!-- <a-tag :color="repair_status === 0 ? 'red' : 'green'">
                            {{ repair_status === 0 ? $t('Not_repaired') : $t('Already_fixed') }}
                        </a-tag> -->
                    </template>
                    <template slot="start_time" slot-scope='start_time'>
                        {{start_time ? start_time : '--'}}
                    </template>
                    <template slot="finish_time" slot-scope='finish_time'>
                        {{finish_time ? finish_time : '--'}}
                    </template>
                </a-table>
            </a-card>
        </a-row>
        <a-modal v-model="visible" :title="$t('Manual_repair')" @ok="handleOk" 
                 :cancelText="$t('Cancel')" :okText="$t('Sure')"
                 :maskClosable="false" v-dragModal>
            <p>{{$t('Manual_repair_tips')}}</p>
            <p style="color: var(--themeColor)">{{$t('Manual_repair_suggestion')}}</p>
        </a-modal>
    </a-row>
</template>
<script>
// import alarm from '../../../static/images/svg/ic_alarm_selected.svg'
// import eliminate from '../../../static/images/svg/ic_eliminate_normal.svg'
import EmptyData from '@/components/common/EmptyData'
import NoAuthPage from '@/components/common/NoAuthPage'

import request from '@/request/request'

export default {
    name:'',
    components: { EmptyData, NoAuthPage },
    data(){
        let self = this;
        return{
            // alarm,
            // eliminate,
            columns:[
                {
                    title: this.$t('Level'),
                    dataIndex: 'severity',
                    key: 'severity',
                    ellipsis: true,
                    width: 120,
                    scopedSlots: {
                        customRender: 'severity'
                    }
                },
                {
                    title: this.$t('Status'),
                    dataIndex: 'repair_status',
                    key: 'repair_status',
                    width: 120,
                    ellipsis: true,
                    scopedSlots: {
                        customRender: 'repair_status'
                    }
                },
                {
                    title: this.$t('Alarm_object'),
                    dataIndex: 'warn',
                    key: 'warn',
                    ellipsis: true,
                },
                {
                    title: this.$t('Reason_des'),
                    dataIndex: 'des',
                    key: 'des',
                    ellipsis: true,
                },
                {
                    title: this.$t('Occur') + this.$t('Time'),
                    dataIndex: 'start_time',
                    key: 'start_time',
                    ellipsis: true,
                    scopedSlots: {
                        customRender: 'start_time'
                    }
                },
                {
                    title: this.$t('Restore') + this.$t('Time'),
                    dataIndex: 'finish_time',
                    key: 'finish_time',
                    ellipsis: true,
                    scopedSlots: {
                        customRender: 'finish_time'
                    }
                }
            ],
            form:this.$form.createForm(this),
            pagination:{
                pageNo: 1,
                // defaultPageSize:10,
                pageSize: 10,
                total:0, //总条数
                showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
                showSizeChanger:true,
                pageSizeOptions: ['10', '15', '20'],
                onShowSizeChange:(current, pageSize)=> {
                    this.pageSize = pageSize
                    self.getdata(this.pagination.pageNo, pageSize)
                },
                onChange:(page,pageSize)=>self.getdata(page,pageSize),//点击页码事件
                buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
            },
            alertData:[],
            records:'',
            ids:'',
            styledata:[],
            spinning:false,
            selectedRowKeys:[],
            levelValue: 0,
            statusValue: 1,
            startTime: '',
            endTime: '',
            visible: false,
            target: '',
            selectTime: [],
            defaultSetting: {emptyText:<EmptyData />},
            alertData_zh: [],
            alertData_en: [],
            rangePickerLocal: {
                "lang": {
                    "placeholder": "Select date",
                    "rangePlaceholder": ["Start date", "End date"],
                    "today": "Today",
                    "now": "Now",
                    "backToToday": "Back to today",
                    "ok": this.$t('Sure'),
                    "clear": "Clear",
                    "month": "Month",
                    "year": "Year",
                    "timeSelect": this.$t('Select-time-picker'),
                    "dateSelect": this.$t('Select-date-picker'),
                    "monthSelect": "Choose a month",
                    "yearSelect": "Choose a year",
                    "decadeSelect": "Choose a decade",
                    "yearFormat": "YYYY",
                    "dateFormat": "M/D/YYYY",
                    "dayFormat": "D",
                    "dateTimeFormat": "M/D/YYYY HH:mm:ss",
                    "monthFormat": "MMMM",
                    "monthBeforeYear": true,
                    "previousMonth": "Previous month (PageUp)",
                    "nextMonth": "Next month (PageDown)",
                    "previousYear": "Last year (Control + left)",
                    "nextYear": "Next year (Control + right)",
                    "previousDecade": "Last decade",
                    "nextDecade": "Next decade",
                    "previousCentury": "Last century",
                    "nextCentury": "Next century"
                },
            }
        }
    },
    computed:{
        getlanguage(){
            return this.$store.state.language
        },
        rowSelection() {
            return {
                // type:"radio",
                // onSelect(record, selected, selectedRows) {
                //     this.target = record;
                // },
                onChange: (selectedRowKeys, selectedRows) => {
                    this.target = selectedRows;
                    this.selectedRowKeys = selectedRowKeys;
                    // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                },
                getCheckboxProps: record => ({
                    props: {
                        disabled: record.repair_status == 1 // Column configuration not to be checked
                    },
                })
            };
        }
    },
    watch: {
        getlanguage(val){  //监听语言切换，切换data组件内的多语言
            this.columns = [
                {
                    title: this.$t('Level'),
                    dataIndex: 'severity',
                    key: 'severity',
                    width: 120,
                    ellipsis: true,
                    align: 'center',
                    scopedSlots: {
                        customRender: 'severity'
                    }
                },
                {
                    title: this.$t('Status'),
                    dataIndex: 'repair_status',
                    key: 'repair_status',
                    width: 120,
                    ellipsis: true,
                    scopedSlots: {
                        customRender: 'repair_status'
                    }
                },
                {
                    title: this.$t('Alarm_object'),
                    dataIndex: 'warn',
                    key: 'warn',
                    ellipsis: true,
                },
                {
                    title: this.$t('Reason_des'),
                    dataIndex: 'des',
                    key: 'des',
                    ellipsis: true,
                },
                {
                    title: this.$t('Occur') + this.$t('Time'),
                    dataIndex: 'start_time',
                    key: 'start_time',
                    ellipsis: true,
                    scopedSlots: {
                        customRender: 'start_time'
                    }
                },
                {
                    title: this.$t('Restore') + this.$t('Time'),
                    dataIndex: 'finish_time',
                    key: 'finish_time',
                    ellipsis: true,
                    scopedSlots: {
                        customRender: 'finish_time'
                    }
                }
            ];
            if(val == 'zh') {
                this.alertData = this.alertData_zh;
            }else {
                this.alertData = this.alertData_en;
            }
            this.rangePickerLocal = {
                "lang": {
                    "placeholder": "Select date",
                    "rangePlaceholder": ["Start date", "End date"],
                    "today": "Today",
                    "now": "Now",
                    "backToToday": "Back to today",
                    "ok": this.$t('Sure'),
                    "clear": "Clear",
                    "month": "Month",
                    "year": "Year",
                    "timeSelect": this.$t('Select-time-picker'),
                    "dateSelect": this.$t('Select-date-picker'),
                    "monthSelect": "Choose a month",
                    "yearSelect": "Choose a year",
                    "decadeSelect": "Choose a decade",
                    "yearFormat": "YYYY",
                    "dateFormat": "M/D/YYYY",
                    "dayFormat": "D",
                    "dateTimeFormat": "M/D/YYYY HH:mm:ss",
                    "monthFormat": "MMMM",
                    "monthBeforeYear": true,
                    "previousMonth": "Previous month (PageUp)",
                    "nextMonth": "Next month (PageDown)",
                    "previousYear": "Last year (Control + left)",
                    "nextYear": "Next year (Control + right)",
                    "previousDecade": "Last decade",
                    "nextDecade": "Next decade",
                    "previousCentury": "Last century",
                    "nextCentury": "Next century"
                }
            };
        }
    },
    mounted(){
        this.getdata(this.pagination.pageNo, this.pagination.pageSize);
    },
    methods:{
        getdata(page,pageSize){
            // console.log((page-1)*pageSize,pageSize*page-1)
            request('get', 'Alert/alerts_mess', {
                    // params: {
                        sort: this.statusValue,
                        status: this.levelValue,
                        start: (page-1)*pageSize, //当前页
                        end: pageSize*page - 1, //每页条数
                        start_time: this.startTime,
                        end_time: this.endTime,
                    // }
            }).then(res=>{
                // console.log('告警信息',res)
                if(this.$i18n.locale == 'zh') {
                    this.alertData = res.data.data;
                }else {
                    this.alertData = res.data.en_result;
                }
                // this.alertData = res.data.data;
                this.alertData_zh = res.data.data;
                this.alertData_en = res.data.en_result;
                this.pagination.total = res.data.count;
            })
        },
        manualRepair(){
            if(this.selectedRowKeys.length == 0){
                this.$notification['error']({
                    message:this.$t('Choose')+this.$t('Operating-object')
                })
                return false
            } else {
                this.visible = true
				// this.selectedRowKeys = []; // 将选择的项清空
            }
            
        },
        handleOk(){
            // 传id数组，批量修复
            let ids = [];
            const instantiation = []
            this.target.forEach(item => {
                ids.push(item.id);
                instantiation.push(item.des)
            })
            request('post', 'Alert/record/repair',{
                // id:this.selectedRowKeys[0],
                // id: this.target[0].id, //单选修复单个
                id: ids, //多选修复多个
                status: 1,
                instantiation
            }).then(res=>{
                // console.log('修复告警返回：', res)
                this.$notification['success']({
                    message: this.$t('Repair-success')
                })
                this.visible = false;
                this.getdata(this.pagination.pageNo, this.pagination.pageSize);
            }).catch(err=>{
                this.$notification['error']({
                    message: err.data
                })
            })
        },
        // 筛选状态
        changeStatus(e) {
            // console.log(`checked = ${e.target.value}`);
            this.statusValue = e.target.value;
            this.getdata(this.pagination.pageNo, this.pagination.pageSize);
        },
        // 筛选级别
        changeLevel(e) {
            this.levelValue = e.target.value;
            this.getdata(this.pagination.pageNo, this.pagination.pageSize);
            console.log(`checked = ${e.target.value}`);
        },
        // 筛选发生时间
        onChange(value, dateString) {
            console.log('Selected Time: ', value);
            console.log('Formatted Selected Time: ', dateString);
            this.startTime = dateString[0]
            this.endTime = dateString[1]
            if(this.startTime == '' && this.endTime == ''){
                this.getdata(this.pagination.pageNo, this.pagination.pageSize);
            }
        },
        onOk(value, dateString) {
            console.log('onOk: ', value, dateString);
            this.getdata(this.pagination.pageNo, this.pagination.pageSize);
        },
        // 重置
        reset(){
            this.levelValue = 0;
            this.statusValue = 1;
            this.startTime = '';
            this.endTime = '';
            this.selectTime = [];
            this.getdata(this.pagination.pageNo, this.pagination.pageSize);
        },
    }
}
</script>
